package io.codegeneratetool.util;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

public class MethodUtil {

	/**
	 * 说明：对当前class类查询指定的方法,如果没有循环其超类查找知道找到
	 * 
	 * @author hub 创建时间2012-11-14下午1:17:04
	 * @param clazz
	 *            当前类
	 * @param methodName
	 *            查询的方法名
	 */
	public static Method getMethod(Class clazz, String methodName) {
		Method declaredMethod = null;
		try {
			declaredMethod = clazz.getDeclaredMethod(methodName);
		} catch (Exception e) {

			Class<?> superclass = clazz.getSuperclass();
			while (superclass != null) {
				try {
					declaredMethod = superclass.getDeclaredMethod(methodName);
					break;
				} catch (Exception e2) {
					superclass = superclass.getSuperclass();
				}
			}

		}
		return declaredMethod;
	}

	/**
	 * 说明：  
	 * @author jiaxf 创建时间2013-1-10下午2:11:52
	 * @param 
	 */
	public static <T extends Annotation> T getAnnotation(Class clazz,
			String methodName, Class<T> annotationClass) {
		Method declaredMethod = null;
		T t = null;
		try {
			declaredMethod = clazz.getDeclaredMethod(methodName);
			t = declaredMethod.getAnnotation(annotationClass);
			if (t == null) {
				Class<?> superclass = clazz.getSuperclass();
				while (superclass != null) {
					try {
						declaredMethod = superclass
								.getDeclaredMethod(methodName);
						t = declaredMethod.getAnnotation(annotationClass);
						if (t != null) {
							return t;
						}else{
							superclass = superclass.getSuperclass();
						}
					} catch (Exception e2) {
						superclass = superclass.getSuperclass();
					}
				}
			}
		} catch (Exception e) {

			Class<?> superclass = clazz.getSuperclass();
			while (superclass != null) {
				try {
					declaredMethod = superclass.getDeclaredMethod(methodName);
					t = declaredMethod.getAnnotation(annotationClass);
					if (t != null) {
						return t;
					}else{
						superclass = superclass.getSuperclass();
					}
				} catch (Exception e2) {
					superclass = superclass.getSuperclass();
				}
			}

		}

		return t;
	}

}
